<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="菜单或者权限名称">
              <a-input placeholder="请输入" v-model="table.role" />
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item label="类型">
              <a-select placeholder="请选择" v-model="table.value" default-value="0">
                <a-select-option value="0">父级菜单</a-select-option>
                <a-select-option value="1">自子级菜单</a-select-option>
                <a-select-option value="2">权限</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="reTable">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="insertRole">新增菜单</a-button>
      <a-popconfirm
        v-if="selectedRowKeys.length > 0"
        title="是否删除这些角色?"
        ok-text="是"
        cancel-text="否"
        @confirm="confirm(selectedRowKeys)"
        @cancel="cancel"
      >
        <a-button type="primary" icon="delete">批量删除</a-button>
      </a-popconfirm>
    </div>
    <a-table
      rowKey="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :columns="columns"
      :data-source="data"
      :loading="loading"
      class="components-table-demo-nested"
      style="margin: 20px"
    >
      <a slot="type" slot-scope="text">
        {{ text | typeFilter }}
      </a>
      <a slot="icon" slot-scope="text">
        <a-icon :type="text" />
      </a>
      <span slot="operation" slot-scope="text, record">
        <a @click="notEdit" v-if="record.code == 'workplace'" style="color: #f40707ff">编辑</a>
        <a @click="$refs.modal.edit(record)" v-else>编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm
          title="是否删除这个角色?"
          ok-text="是"
          cancel-text="否"
          @confirm="confirm(record)"
          @cancel="cancel"
        >
          <a href="javascript:;">删除</a>
        </a-popconfirm>
      </span>
    </a-table>
    <role-modal ref="modal" @ok="handleOk"></role-modal>
  </a-card>
  <!-- 抽屉 -->
</template>

<script>
import { STable } from '@/components'
import RoleModal from './modules/MenuModal'
const columns = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '类型', dataIndex: 'type', key: 'type', scopedSlots: { customRender: 'type' } },
  { title: '路由路径', dataIndex: 'path', key: 'path' },
  { title: '菜单/权限标记', dataIndex: 'code', key: 'code' },
  { title: '图标', dataIndex: 'icon', key: 'icon', scopedSlots: { customRender: 'icon' } },
  { title: '排序', dataIndex: 'sort', key: 'sort' },
  { title: '备注', dataIndex: 'remarks', key: 'remarks' },
  { title: '操作', key: 'operation', scopedSlots: { customRender: 'operation' }, align: 'center' }
]

const STATUS = {
  0: '启用',
  1: '禁用'
}
const IconSTATUS = {
  0: '父级菜单',
  1: '子级菜单',
  2: '权限'
}

export default {
  name: 'TableList',
  components: {
    STable,
    RoleModal
  },
  data() {
    return {
      selectedRowKeys: [],
      data: [],
      columns,
      defalutSelect: [],
      treeData: [],
      loading: false,
      drawerVisible: false,
      replaceFields: {
        children: 'child',
        title: 'name'
      },
      description:
        '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',

      visible: false,
      table: {
        role: '',
        value: '0'
      },

      form: this.$form.createForm(this),
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头

      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      selectedRows: [],
      Roleid: ''
    }
  },
  created() {
    this.getTable()
    this.getsyspression()
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
    typeFilter(key) {
      return IconSTATUS[key]
    },
    moment(value) {
      return new Date(value).toLocaleString() // 你可以根据需要修改格式
    }
  },
  methods: {
    notEdit() {
      this.$message.error('这项不可以修改哦')
    },
    getsyspression() {
      const pages = {
        pageNo: 0,
        pageSize: 10,
        params: {
          id: '',
          createTime: '',
          remarks: '',
          type: 0,
          parentId: '',
          name: '',
          englishName: '',
          path: '',
          code: '',
          outerChain: 0,
          icon: '',
          sort: 0,
          children: [
            {
              id: '',
              createTime: '',
              remarks: '',
              type: 0,
              parentId: '',
              name: '',
              englishName: '',
              path: '',
              code: '',
              outerChain: 0,
              icon: '',
              sort: 0,
              children: [{}],
              tree: true
            }
          ],
          tree: true
        }
      }
      this.$http.post('/sysPermission/page', pages).then((res) => {
        if (res.code === 200) {
          // console.log('选择数据', res.result.records)
          const aa = this.convertToTreeData(res.result.records)
          // console.log('树结构数据', aa)

          this.treeData = aa
        }
      })
    },
    convertToTreeData(rawData) {
      // 树形装换
      return rawData.map((item) => {
        const transformedItem = {
          title: item.name, // 使用 name 字段作为 title
          key: item.id, // 使用 id 作为 key
          scopedSlots: { icon: 'custom' }, // 自定义图标插槽
          icon: item.icon || 'smile', // 使用 icon 字段，如果没有则为空
          children: item.children ? this.convertToTreeData(item.children) : null // 递归处理子节点
        }
        return transformedItem
      })
    },
    onSelect(selectedKeys, info) {
      console.log('selected', selectedKeys, info)
    },
    onCheck(checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
      this.defalutSelect = checkedKeys.checked
      const aak = {
        roleId: this.Roleid,
        check: info.checked,
        permission_id: checkedKeys.checked
      }
      this.$http.post('/sysRole/check', aak).then((res) => {
        console.log('是否成功', res)
      })
      console.log('角色及权限', aak)
    },
    afterVisibleChange(val) {
      // console.log('drawerVisible', val)
    },
    onClose() {
      this.drawerVisible = false
    },
    editpermission(e) {
      this.drawerVisible = true
      console.log('角色id', e)
      this.Roleid = e.id
      this.$http.get(`/sysRole/getPermission/${e.id}`).then((res) => {
        // console.log('选中的数据', res)
        if (res.code === 200) {
          this.defalutSelect = res.result
        }
        // console.log('数据', this.defalutSelect)
      })
    },

    confirm(e) {
      console.log(111, e)
      var value = []
      if (Object.prototype.toString.call(e) === '[object Object]') {
        // console.log('单个删除')
        value.push(e.id)
      } else {
        value = e
      }
      // console.log(222, this.selectedRowKeys)
      console.log(value)
      this.$http.post('/sysPermission/delete', value).then((res) => {
        if (res.code === 200) {
          this.getTable()
          this.$message.success('删除成功')
        }
      })

      //
    },
    cancel(e) {
      console.log(e)
      // this.$message.error('Click on No')
    },

    insertRole() {
      this.$refs.modal.add()
    },
    search() {
      console.log(this.table)
      // if (this.table.value !== '2') {
      const roleList = this.removeSpacesFromObject(this.table)
      console.log(roleList)
      const dataparams = { name: roleList.role, type: roleList.value, tree: true }
      this.loading = true
      this.$http.post('/sysPermission/getadd', dataparams).then((res) => {
        if (res.code === 200) {
          this.data = []
          this.loading = false
          this.data = res.result
        }
      })
      // } else {
      //   this.getTable().
      // }
    },
    reTable() {
      console.log(this.table)
      this.table = {
        role: '',
        value: '0'
      }
    },
    removeSpacesFromObject(obj) {
      // 去除对象中的每一项数据的空格
      // console.log('obj', obj)

      const newObj = {}
      Object.keys(obj).forEach((key) => {
        newObj[key] = obj[key].replace(/\s+/g, '') // 去除所有空格
      })
      return newObj
    },
    handleExpand(expanded, record) {
      // console.log('expanded', expanded, record)
      // if (expanded) {
      //   this.expandedRowKeys.push(record.id)
      // } else {
      //   this.expandedRowKeys = this.expandedRowKeys.filter((item) => record.id !== item)
      // }
    },
    plsc() {
      console.log('批量删除')
    },
    onSelectChange(selectedRowKeys) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    getTable() {
      this.loading = true
      const menuParams = {
        id: '',
        createTime: '',
        remarks: '',
        type: 0,
        parentId: '',
        name: '',
        englishName: '',
        path: '',
        code: '',
        outerChain: 0,
        icon: '',
        sort: 0,
        children: [
          {
            id: '',
            createTime: '',
            remarks: '',
            type: 0,
            parentId: '',
            name: '',
            englishName: '',
            path: '',
            code: '',
            outerChain: 0,
            icon: '',
            sort: 0,
            children: [],
            tree: true
          }
        ],
        tree: true
      }
      this.$http.post('/sysPermission/getadd', menuParams).then((res) => {
        if (res.code === 200) {
          this.loading = false
          // console.log('菜单', res)
          // 确保每个对象的 key 值唯一
          this.data = res.result
          // this.loadData = res.result
          // this.expandedRowKeys = res.result.map((item) => item.id)
        }
      })
    },
    handleEdit(record) {
      this.mdl = Object.assign({}, record)

      this.mdl.permissions.forEach((permission) => {
        permission.actionsOptions = permission.actionEntitySet.map((action) => {
          return { label: action.describe, value: action.action, defaultCheck: action.defaultCheck }
        })
      })

      // console.log(this.mdl)
      this.visible = true
    },
    handleOk() {
      this.getTable()
      this.$refs.modal.close()
      // 新增/修改 成功时，重载列表
      // this.$refs.table.refresh()
    },
    onChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
